package org.epidroid.epidroid.androsoul.engine.contacts;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.util.Iterator;

import org.epidroid.epidroid.androsoul.engine.AndroSoul;

import android.util.Log;

public class ContactsLoader {

	// / Stream in which to save the contacts
	private FileInputStream _fis = null;
	private ObjectInputStream _ois = null;
	private AndroSoul _androsoul = null;

	public ContactsLoader(AndroSoul androsoul, FileInputStream fis)
			throws StreamCorruptedException, IOException {
		super();
		_androsoul = androsoul;
		this._fis = fis;
		_ois = new ObjectInputStream(fis);
	}

	public void close() {
		try {
			_ois.close();
			_fis.close();
		} catch (IOException e) {
			Log.v(AndroSoul.LOGCAT, e.getMessage());
		}
	}

	public void finalize() {
		close();
	}

	public ContactGroup cloneGroup(ContactGroup group) {
		ContactGroup cloned = new ContactGroup(_androsoul, group.getName());

		Iterator<NetsoulContact> it = group.iterator();
		while (it.hasNext()) {
			NetsoulContact tmp = it.next();
			cloned.add(tmp.getName());
		}

		return cloned;
	}

	/**
	 * Load contacts in the given contact group
	 */
	public void load(Contacts c) {
		try {
			Contacts contacts = (Contacts) _ois.readObject();
			Iterator<ContactGroup> it = contacts.iterator();
			while (it.hasNext()) {
				ContactGroup tmp = it.next();
				c.addGroup(cloneGroup(tmp));
			}
		} catch (IOException e) {
			Log.v(AndroSoul.LOGCAT, e.getMessage());
		} catch (ClassNotFoundException e) {
			Log.v(AndroSoul.LOGCAT, e.getMessage());
		}
		close();
	}
}
